<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/7/24
 * Time: 9:43
 */

namespace App\GameService\games;


use App\Common\AuthCommon;
use App\Common\BaseComm;
use App\Common\GameCommon;
use App\Enum\CardEnum;
use App\Enum\ZjhEnum;
use App\Model\GameType;
use App\Utility\BaseEnum;
use Swoole\Timer;

class PlayZhaJinHua extends BasePlay
{
    public function __construct(){
        $this->gtimeConfig = [
            "firstcard_long" => 2,      //初始化时长
            "everybet_long" => 10,      //第个玩家等待下注时长
            "waitdeal_long" => 5,       //发牌完成完成，等待结算时长
        ];
    }

    /**发牌加上牌型,适用于炸金花
     * @param $gameId
     * @param $gameNo
     */
    public function createCardList($gameId,$gameNo,$seatList=false){
        //必须是按炸金花牌规则排好序的牌型
        $useCards = GameCommon::createCardList($gameId,$gameNo,$seatList);
        //添加牌型下标
        foreach ($useCards as &$v){
            $cards = $v['cards'];
            $weight = ZjhEnum::getCardsWeight($cards,$level);
            $v['cardsLevel'] = $level;
            $v['cardsWeight'] = $weight;
        }
        return $useCards;

    }

    /**
     * @param $gameNo
     * @param bool $gameRId
     * @param bool $players 玩家匹配成功返回的数据
     * @param bool $fjInfo
     * @return bool
     */
    public function asycStartGame($gameNo, $gameRId=false, $players = false,$fjInfo = false){
        if(!$players) return false;//匹配玩家返回的信息
        $betLong = $this->getConfigTimeLong('everybet_long') ?? 10;
        $Long = $this->getConfigTimeLong('firstcard_long') ?? 2;
        $fjDetail = BaseComm::distMemoryRooms($gameNo,false);
        $fjSta = isset($fjDetail['fjStatus']) ? intval($fjDetail['fjStatus']) : 0;//完成匹配状态
        $playList = isset($fjDetail['lists']) ? $fjDetail['lists'] : false;//玩家列表
        $playFds = !empty($playList) ? array_column($playList,'fd',"seatNo") : false;

        BaseEnum::Logger("取内存数据:Games-(PlayZhaJinHua)-[asycStartGame]--->>>".json_encode($fjDetail),'user-login');

        if (!$fjInfo || empty($fjInfo)){
            $fjInfo = BaseComm::GameRoomDetail($gameRId);
        }
        $gameId = isset($fjInfo['gameId']) ? intval($fjInfo['gameId']) : 0;
        //刚开始就给玩家生成牌的数据
        $useCards = $this->createCardList($gameId,$gameNo,false);
        BaseEnum::Logger("游戏开始生成牌：Game-(PlayZhaJinHua)-[asycStartGame]--->>".$gameId.'---'.$gameNo.'---'.json_encode($useCards),"user-login");
        if (!$useCards) return false;
        //随机一名玩家先进行操作
        $useCards = array_column($useCards,null,'seatNo');
        //返回客户端数据
        $gameResult['gstart'] = 1;
        $gameResult['gameNo'] = $gameNo;
        $gameResult['deskMoney'] = $fjDetail['deskMoney'] ?? 0;
        $gameResult['currRound'] = $fjDetail['currRound'] ?? 1; //当前回合
        $currSeatNo = array_rand($playFds,1);
        $gameResult['currSeatNo'] = $currSeatNo; //下一个要操作的玩家
        $gameResult['nextWaitTime'] = $betLong; //下个定时器等待时长
        //房间底注和顶注信息
        $selectChips = GameCommon::getRoomsChips($gameRId);
        if(!$selectChips) return false;
        $bottomChip = min($selectChips)/2;
        $topChip = max($selectChips)*2;
        $gameResult['roomInfo'] = [
            "gameId"=>$gameId,
            "everyPoints"=>$fjInfo['everyPoints'] ?? 1, //下注最低分数,底分
            "smallPoints"=>$fjInfo['smallPoints'],// 最低准入分数
            "total"=>$fjInfo['playNumber'], //至少玩的局数,1
            "bottomChip" => $bottomChip,//底注
            "topChip" => $topChip,//顶注
        ];
        //匹配返回的玩家列表和内存玩家列表都加上牌型等级,筹码值，跟注和比牌下注金额
        foreach ($useCards as $seatNo => $cards) {
            $wjInfo = $playList[$seatNo] ?? false;
            if($wjInfo){
                $wjInfo['cards'] = $cards['cards'];
                $wjInfo['cardsLevel'] = $cards['cardsLevel'];
                $wjInfo['cardsWeight'] = $cards['cardsWeight'];
                $wjInfo['pstatus'] = ZjhEnum::GAME_STEP_1;
                $wjInfo['chips'] = $selectChips;//加注筹码值
                $wjInfo['minBet'] = $bottomChip;//最小下注（跟注和比牌下注金额）
                $playList[$seatNo] = $wjInfo;
            }

            if(isset($players[$seatNo])){
                $players[$seatNo]['cards'] = $cards['cards'];
                $players[$seatNo]['cardsLevel'] = $cards['cardsLevel'];
                $players[$seatNo]['chips'] = $selectChips;//加注筹码值
                $players[$seatNo]['minBet'] = $bottomChip;//最小下注（跟注和比牌下注金额）
            }
        }
        $fjDetail['currSeatNo'] = $currSeatNo;
        $fjDetail['lists'] = $playList;
        $gameResult['players'] = $players;
        BaseComm::distMemoryRooms($gameNo,true,$fjDetail);
        $this->setGameStatus("P-" .ZjhEnum::GAME_STEP_1); // 设置游戏状态,发牌完成；
        BaseEnum::Logger("初始进入房间返回数据：Games-(PlayZhaJinHua)->---->>>" . json_encode($gameResult), 'user-login');
        if (!empty($playFds)) {
            AuthCommon::pushFrontWeb($playFds, json_encode([ 'm' => BaseEnum::XYM_0X16, "data" => $gameResult])); // 推送相同内容
        }
        BaseEnum::Logger("第一轮表态：Games-(PlayZhaJinHua)->  从玩家[siteNo={$gameResult['currSeatNo']}]开始---->>>" . json_encode($playFds), 'user-login'); // 所有玩家FD
        //发送数据后2秒等待前台动画执行，进入第一轮等待玩家操作
        sleep($Long);
        $this ->waitPlayerHander($gameNo, $playFds,$fjSta,$currSeatNo,1);
    }

    //TODO 异步操作（可以提前中断的功能）
    protected function asycLoading($sleepTime,$gameNo,$callBackFun = null) {
        //倒计时的内容放在内存变量中
        PlayHelp::getInstance()->setLoopTim($gameNo,$sleepTime);
        //TODO 启用定时器；推送倒计时给前端
        $this->tempLoadTimer = Timer::tick(1000, function() use ($gameNo,$callBackFun, $sleepTime){
            $myVal = PlayHelp::getInstance()->getLoopTim($gameNo);
            $myVal = $myVal - 1;
            PlayHelp::getInstance()->setLoopTim($gameNo,$myVal);                    // 保存修改后的值
            $loopTimerStop = PlayHelp::getInstance()->getCommTimerStop($gameNo);    //停掉定时器
            if (intval($myVal) <= 0 || $loopTimerStop === true) {                   //特殊情况中断倒计时数据；
                Timer::clear($this->tempLoadTimer);
                $this->tempLoadTimer = null;
                PlayHelp::getInstance()->setCommTimerStop($gameNo,FALSE);           //unset(Games::$gameCommonTimer[$gameNo]);    //清空数据
                BaseEnum::Logger("临时等待定时器工作结束：(clear)-倒计时结束执行功能： [tempLoadTimer]--->>>>loop={$loopTimerStop}----->". $gameNo, 'user-login');
                if($callBackFun !== FALSE){
                    @call_user_func($callBackFun);                                  //回调方案
                }
            }
        });
    }

    /**
     * TODO 玩家表态等待10时间；
     * @param string $gameNo 局号
     * @param array $playFds 玩家FD
     * @param number $fjStatus 状态
     * @param boolean $currSeatNo 下一位玩家的座位号
     */
    protected function waitPlayerHander($gameNo,$playFds,$fjStatus=0,$currSeatNo = FALSE , $gameLun = 1) {
        $betLong = $this->getConfigTimeLong('everybet_long') ?? 10; //玩家下注等待时长
        //TODO 表态定时器等待 ====倒计时10秒钟
        $this->asycLoading($betLong,$gameNo,function () use ($gameNo, $playFds,$fjStatus,$currSeatNo,$gameLun,$betLong) {
            usleep(800);
            //TODO： 第一轮表态：当前玩家没有表态自动表态
            $fjDetail = BaseComm::distMemoryRooms($gameNo,FALSE);
            $deskMoney = isset($fjDetail["deskMoney"]) ? floatval($fjDetail["deskMoney"]) : 0;

            //TODO　操作后向全部玩家推送数据,跟注和加注筹码(根据上一个玩家加注数据和玩家看牌与否决定)
            $pushPlayer = [
                "seatNo" => $currSeatNo,//当前操作玩家
                "roundType" => -1,//本轮操作类型
                "roundMoney" => 0,//玩家本轮下注金额
                "totalMoney" => 0,//玩家总共下注

                "deskMoney" => $deskMoney,//牌桌总筹码值玩家本轮有处理，不改变
                "currRound" => $gameLun,//当前操作属于第几轮
                "nextWaitTime"=>$betLong,//下个定时器等待时长
                //后面更新
                "nextSeatNo" => -1,//下一个玩家座位号
                "nextMinBet" => 0,//下一个玩家跟注和比牌筹码值
                "nextChips" => [],//推送给下个玩家的加注筹码值

            ];

            $gamePlays = isset($fjDetail['lists']) ? $fjDetail['lists'] : FALSE;// 玩家列表；

            $currUser = isset($gamePlays[$currSeatNo]) ? $gamePlays[$currSeatNo] : FALSE ;//当前操作玩家
            $roundIndex = isset($currUser['roundIndex']) ? intval($currUser['roundIndex']) : $gameLun-1;//默认前一轮
            $roundType = isset($currUser['roundType']) ? intval($currUser['roundType']) : -1 ;//默认没有操作
            $roundMoney = isset($currUser['roundMoney']) ? floatval($currUser['roundMoney']) : 0.00 ;//前一轮或本轮的下注金额
            $totalMoney = isset($currUser['totalMoney']) ? floatval($currUser['totalMoney']) : 0.00 ;//前一轮或本轮的下注总额
            $minBet = isset($currUser['minBet']) ? floatval($currUser['minBet']) : 0.00; //当前最小下注
            $enableSeat = $fjDetail['enableSeatNo'] ?? array_column($gamePlays,'seatNo','seatNo');//当前可操作座位号

            //TODO 已弃牌不参与自动处理
            if ($roundType !== ZjhEnum::HANDLE_TYPE_0) {
                //TODO  是否已经表态过
                if ($roundIndex && $roundIndex === $gameLun) {       //是否已操作
                    BaseEnum::Logger("玩家表态查询：第{$roundIndex}轮---已表态：{$roundType}，分数 ：{$roundMoney}]，不执行存储内存数据 -->" . json_encode($currUser), 'user-login'); // 所有玩家FD
                }else{
                    $prevent = isset($currUser['preventDiscard']) ? $currUser['preventDiscard'] : 1;  //默认防超时弃牌
                    $currCardStatus = $currUser['cardStatus'] ?? 0; //默认没看牌
                    $currCardsLevel = $currUser['cardsLevel'] ?? ZjhEnum::GAME_0X21;//默认高牌
                    //TODO 玩家未操作[未表态]  ====> 交给系统处理：弃牌or跟牌
                    if($prevent == 1 && $currCardStatus == 1){
                        //看牌情况下，不可比牌阶段超时未操作且牌型为顺子以上会自动跟注
                        if($gameLun = 1 && $currCardsLevel >= ZjhEnum::GAME_0X23){
                            $currUser['roundType'] = ZjhEnum::HANDLE_TYPE_2;
                            $currUser['roundMoney'] = $currUser['minBet'];
                            $currUser['totalMoney'] = floatval(bcadd($totalMoney,$minBet,3));
                            $fjDetail['deskMoney'] = floatval(bcadd($deskMoney,$minBet,3));
                         }else if($gameLun >=2 && $currCardsLevel >= ZjhEnum::GAME_0X23){
                            //超时触发比牌
                            $seatArr = $enableSeat;
                            unset($seatArr[$currSeatNo]);
                            $otherSeatNo = array_rand($seatArr,1);
                            $otherUser = $gamePlays[$otherSeatNo];
                            ZjhEnum::gatherWhoWin($currUser,$otherUser,$payPlayer);
                            $currUser['roundType'] = ZjhEnum::HANDLE_TYPE_1;
                            $currUser['roundMoney'] = $currUser['minBet'];
                            $currUser['totalMoney'] = floatval(bcadd($totalMoney,$minBet,3));
                            $fjDetail['deskMoney'] = floatval(bcadd($deskMoney,$minBet,3));
                        }else{
                            //弃牌
                            $currUser['roundType'] = ZjhEnum::HANDLE_TYPE_0;
                            $currUser['roundMoney'] = 0.00;
                            unset($fjDetail['enableSeatNo'][$currSeatNo]);
                            BaseEnum::Logger("玩家表态查询：第{$gameLun}轮--- !!!!未表态!!!! 防超时弃牌：{$prevent},看牌状态：{$currCardStatus},牌型cardsLevel：{$currCardsLevel}小于顺子=> 系统自动弃牌-->" . json_encode($currUser), 'user-login');
                        }
                    }else{
                        //默认本轮弃牌
                        $currUser['roundType'] = ZjhEnum::HANDLE_TYPE_0;
                        $currUser['roundMoney'] = 0.00;
                        unset($fjDetail['enableSeatNo'][$currSeatNo]);
                        BaseEnum::Logger("玩家表态查询：第{$gameLun}轮--- !!!!未表态!!!! 玩家未勾选防超时弃牌或者没看牌情况下系统自动弃牌-->" . json_encode($currUser), 'user-login');
                    }
                    $currUser['rounIndex'] = $gameLun;
                    $gamePlays[$currSeatNo] = $currUser;
                    $fjDetail["lists"] = $gamePlays;
                }

            }
            //TODO 当前位置弃牌要推送出去，并且带上下一位玩家跟牌比牌筹码值和加注筹码值
            //修改房间内存
            $fjDetail["fjStatus"]   = ZjhEnum::GAME_STEP_2;   //房间状态
            $fjDetail["lastSeatNo"] = $currSeatNo;            //记录最后一个玩家位索引
            $fjDetail["currRound"]  = $gameLun ;              //记录轮数
            //默认和不默认的一起推送数据
            $pushPlayer['roundType'] = $currUser['roundType'] ?? -1;
            $pushPlayer['deskMoney'] = $fjDetail['deskMoney'] ?? 0;
            $pushPlayer['roundMoney'] = $currUser['roundMoney'] ?? 0;
            $pushPlayer['totalMoney'] = $currUser['totalMoney'] ?? 0;
//            $pushPlayer['nextSeatNo'] = GameCommon::getSeat($currSeatNo,$enableSeat,'next');
            BaseComm::distMemoryRooms($gameNo,TRUE,$fjDetail);  //更新表态数据到内存中处理（用户自己操作，和系统默认弃牌处理 ）;
            BaseEnum::Logger("表态完成：(waitPlayerHander)->  玩家[siteNo={$currSeatNo}__play---->{$currUser['roundType']},下注：{$currUser['roundMoney']}] 操作表态 [ SUCCESS ] !!=>" . json_encode($currUser), 'user-login'); // 所有玩家FD

            //TODO 检测所有玩家(  1、玩家弃牌，最后一个人赢结束 ， 2、没结束 继续后面的 每轮下注)
            ////重新获取内存，可能其他玩家提前弃牌,$enableSeat发生改变
            $fjDetail = BaseComm::distMemoryRooms($gameNo,false);
            BaseEnum::logger("表态完成重新获取房间信息".json_encode($fjDetail));
            $gamePlays = isset($fjDetail['lists']) ? $fjDetail['lists'] : FALSE;
            $enableSeat = $fjDetail['enableSeatNo'] ?? [];

            if ($enableSeat){
                //剩下一个人成为赢家
                if (sizeof($enableSeat)==1){
                    $finalSeatNo = current($enableSeat);
                    $finalUser = $gamePlays[$finalSeatNo];
                    $pushPlayer['nextSeatNo'] = -1000;//剩下一个玩家时推送数据
                    $pushdata = [
                        'm'=>BaseEnum::XYM_0X73,
                        'data'=>$pushPlayer
                    ];
                    AuthCommon::pushFrontWeb($playFds,json_encode($pushdata));

                    BaseEnum::Logger("第{$gameLun}轮弃牌提前结束：(waitPlayerHander)->获胜玩家=>" . json_encode($finalUser), 'user-login'); // 所有玩家FD
                    BaseEnum::Logger("内存数据 =>" . json_encode($fjDetail), 'user-login');          // 所有玩家FD
                    $gameRId = isset($fjDetail["grid"]) ? intval($fjDetail["grid"]) : 0;            //房间 ID
                    $deskMoney = isset($fjDetail["deskMoney"]) ? floatval($fjDetail["deskMoney"]) : 0;

                    //TODO 比牌前赢的钱都是当前这个桌面上的所有钱 (桌面上多少钱)；
                    foreach ($gamePlays as $settno => $userdet){
                        $oneUid = isset($userdet['uid']) ? intval($userdet['uid']) :0 ;
                        $oneHand = isset($userdet['roundType']) ? intval($userdet['roundType']) : -1 ;
                        $totalMoney = isset($userdet['totalMoney']) ? floatval($userdet['totalMoney']) :0 ; //玩家自己下注金额；
                        $xjMoney = $xjBetMoney = $water2 = 0;
                        if($oneUid <= 0) continue;
                        if($settno != $finalSeatNo){
                            //弃牌和比牌失败的玩家
                            $xjMoney = 0 - $totalMoney;
                            $xjBetMoney = ($xjMoney < 0) ? abs($xjMoney) : 0;
                        }else{
                            $xjMoney = $fjDetail['deskMoney'] ?? 0.00;
                            $xjMoney = bcsub($deskMoney,$totalMoney,3);
                            //最后一个玩家赢的玩家拿走所有桌面上的钱
                            $water2 = bcmul(BaseComm::getSetWaterDott(), $xjMoney ,3);         //抽水的钱
                            $xjBetMoney = bcsub($xjMoney , $water2 , 3);                      //有效下注
                        }

                        // 结算金额的钱值
                        $userRes[$settno] = array(
                            "uid" => $oneUid,
                            "seatNo" => $settno,
                            "money"  => floatval($xjMoney),         //盈亏值
                            "eachprice" => floatval($xjBetMoney),   //有效下注(正数)
                            "level"  => 1 ,
                            "card_mutle" => 1,
                            "water"  =>   floatval($water2),
                        );
                    }
                    //处理完
                    BaseEnum::Logger("弃牌结算：所有玩家盈亏状态 =>" . json_encode($userRes), 'user-login'); // 所有玩家FD

                    //结算订单操作
                    $this -> dealGameUserOrder($gameRId,$gameNo,$userRes,$gamePlays);
                    return FALSE;

                }else if(sizeof($enableSeat) > 1){
                    //TODO 本轮是否可以结束,本轮所有玩家都已操作
                    $isFinish = true;
                    foreach ($enableSeat as $seatNo) {
                        $everyPlayer =  $gamePlays[$seatNo] ?? false;
                        if($everyPlayer['roundIndex'] < $gameLun){
                            $isFinish = false;
                            break;
                        }
                    }
                    //TODO 查询下一位玩家
                    $nextSeatNo = GameCommon::getSeat($currSeatNo,$enableSeat,'next');
                    $nextUser = $gamePlays[$nextSeatNo] ?? false;

                    if($isFinish === TRUE){
                        //TODO 满足下一轮操作；内存和推送的当前轮改为下一轮
                        $nextLun = $gameLun + 1;
                        $fjDetail['currRound'] = $nextLun;
                        $pushPlayer['currRound'] = $nextLun;
                        BaseEnum::Logger("第{$gameLun}轮[ALL--表态--FINISH ]表态完成：(waitPlayerHander)->  进入第{$nextLun}轮 [currSeatNo={$currSeatNo}]--SUCCESS-->>>" . json_encode($gamePlays), 'user-login'); // 所有玩家FD
                    }
                    $fjDetail['currSeatNo'] = $nextSeatNo;
                    BaseComm::distMemoryRooms($gameNo,true,$fjDetail);
                    //TODO 推送当前玩家的  操作数据
                    $pushPlayer['nextSeatNo'] = $nextSeatNo;
                    $pushPlayer['nextMinBet'] = $nextUser['minBet'] ?? 0.00; //下家跟注比牌筹码值
                    $pushPlayer['nextChips']  = $nextUser['chips'] ?? [];  //下家玩家筹码值
                    $pushdata = array('m'=>BaseEnum::XYM_0X73,"data"=> $pushPlayer);
                    AuthCommon::pushFrontWeb($playFds,json_encode($pushdata));
                    @sleep(2); //TODO  下一位玩家开始表态
                    $this ->waitPlayerHander($gameNo, $playFds,$fjStatus,$nextSeatNo , $gameLun);
                }
            }else{
                return false;
            }
        });
    }

    /**
     * TODO 结算订单操作
     仅剩下一名玩家的时候结算
     * @param int $gameRId
     * @param string $gameNo
     * @param array $dealRes
     * @return number
     */
    protected function dealGameUserOrder($gameRId,$gameNo,$dealRes,$players = FALSE) {
        $gameModel = new GameType();
        //结果出来后，要操作对应的用户身份上；
        $tbDisplayName = $gameModel->tbRoomDisplayName;
        //测试数据
        $returndata = ['cardvalues' =>  '23434234;2343434234'] ;
        $cardValue = isset($returndata['cardvalues']) ? $returndata['cardvalues'] :"";
        //去取玩家要下注的房间信息
        $fjInfo = $gameModel -> getGameTableDetail($gameNo);

        $gameDetail = BaseComm::distMemoryRooms($gameNo,FALSE);

        $gameId = $gameDetail['gameId'] ?? 0;

        $players = $players ?? $gameDetail['list'];

        if(!empty($players) && !empty($dealRes) && !empty($returndata) && !empty($cardValue) && !empty($gameDetail) && $gameId > 0 ) {
            //把玩家的订单信息补全；
            $userIds = array_column($players, "uid","seatNo");
            $userFds = array_column($players, "fd","seatNo");

            //组状下注信息；（闲家下注）
            $editData = [];
            $playOrder = GameCommon::createUserOrderFrom(implode(',', $userIds) , $fjInfo, $editData,true,$players);     //玩家订单信息

            if(!empty($playOrder)){
                $gameModel->dbConnector() -> insertMulti("qc_games_orders", $playOrder) ;
            }else{
                BaseEnum::Logger('订单出错：(dealGameUserOrder---Error)===-->' . json_encode($playOrder), 'user-login');
                return FALSE;
            }

            //桌子信息==> 更新用户的输赢信息；
            $errorCode = -1;

            //结算订单数据；
            //操作相关的注单信息；1、修改订单状态，补全订单信息； 2、用户资金交易数据处理； 3、收拾桌面数据，匹配列表清空；
            $result = GameCommon::dealUserOrder($gameRId,$gameNo,$dealRes,$returndata,$errorCode);
            BaseEnum::Logger('输出结果：(Result)=>' . json_encode($result), 'user-login');

            $playCards = BaseComm::distMemoryCards($gameNo,FALSE);
            BaseEnum::Logger('玩家所有手牌：(playCards)=>' . json_encode($playCards), 'user-login');

            //操作数据 ＝＝＝＝ 组装成 WEB端要用的数据；
            if(!empty($result) && sizeof($result) > 0){ //结算成功；
                foreach ($dealRes as $r => $dealobj){
                    $cardLev = -1;
                    $cardName = '';
                    $oneuid = isset($dealobj['uid']) ? intval($dealobj['uid']):0 ;
                    $oneSid = isset($dealobj['seatNo']) ? intval($dealobj['seatNo']):0 ;
                    $ucards = (isset($playCards[$oneSid]) && !empty($playCards[$oneSid])) ? $playCards[$oneSid] : [];
                    $oneArr = isset($result[$oneuid]) ? $result[$oneuid]:FALSE ;
                    $useChangeFee = isset($oneArr['changeMoney']) ? floatval($oneArr['changeMoney']) :0 ;
                    if(!empty($oneArr) && isset($oneArr['points'])){
                        $dealRes[$r]["points"] = floatval($oneArr['points']);
                        $dealRes[$r]["changeMoney"] = $useChangeFee;
                        $dealRes[$r]["cards"] = (!empty($notGiveupIds) && in_array($oneuid, $notGiveupIds) ) ? $ucards : [];    // 玩家手里牌(只有未弃牌的玩家才会显示手牌)
                        $dealRes[$r]["maxCards"] = [];
                        if(!empty($notGiveupIds) && in_array($oneuid, $notGiveupIds)){
                            $getCa = $maxUserCards[$r] ?? FALSE;
                            $cardLev = $getCa['level'] ?? 0;
                            $cardName = $getCa['name'] ?? "";
                            $cardval = (isset($getCa['cards']) && !empty($getCa['cards']))  ? explode(',', $getCa['cards']) : []; //最大牌值
                            $dealRes[$r]["maxCards"] = $cardval;    //TODO 玩家手中与桌面组成的最大牌型数据
                        }
                        $dealRes[$r]["level"] = $cardLev;
                        $dealRes[$r]["maxCardsName"] = $cardName;
                    }
                }

                //把牌局信息补全；
                $editDisplay = ["playerInfo"=> json_encode($dealRes,JSON_FORCE_OBJECT),"finishDateTime"=> BaseEnum::getNowTime(true),"openStatus" => 2];
                $whertOpt = ["roomId"=>$gameRId,"gameNo"=> $gameNo];

                $reds = DBTools::PoolUpdate($tbDisplayName,$editDisplay,$whertOpt);

                //TODO 数据成功 推送：所有牌数据和输赢
                if(isset($reds) && intval($reds) > 0 && !empty($dealRes)){
                    $gameDoRealNum = sizeof($gameDetail['lists']);  //真实人数统计
                    BaseEnum::Logger("结算完成：(dealPlayMoney玩家数：{$gameDoRealNum}位)===[SUCCESS] 补全牌局信息--> res:".$reds. "==== " . json_encode($editDisplay), 'user-login');
                    //修改房间和用户操作状态
                    $gameDetail['fjStatus'] = ZjhEnum::GAME_STEP_3;
                    if (isset($gameDetail['lists']) && ! empty($gameDetail['lists'])) {
                        foreach ($gameDetail['lists'] as $setiid => $fg) {
                            $gameDetail['lists'][$setiid]["pstatus"] = ZjhEnum::GAME_STEP_3;
                        }
                    }
                    BaseComm::distMemoryRooms($gameNo, TRUE, $gameDetail); // 保存用户数据

                    //TODO 前端结算
                    $pushArray = ['m' => BaseEnum::XYM_0X1C,"data" => $dealRes];
                    AuthCommon::pushFrontWeb($userFds, json_encode($pushArray));

                    //TODO 在线玩家数据（游戏结束，在线人数减少）
                    BaseComm::changeOnLines($gameId,$gameDoRealNum,1);
                    BaseComm::distLastGameNoListRedis($userIds,TRUE,FALSE); //清掉最新局
                    return TRUE;
                } else {
                    BaseEnum::Logger('炸金花结算处理：结算失败 ！！！！PlayNiuNiu-(asycWaitDealCenter)-；======>  ' . print_r($dealRes, true), 'user-login');
                    return false;
                }
                return TRUE;     //数据处理成功；返回内容；
            }
        }
    }









}